package com.star.cat.persitent.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.star.cat.common.utils.TreeUtil;
import com.star.cat.common.vo.CacheNode;
import com.star.cat.common.vo.CacheVo;
import com.star.cat.persitent.model.PerModel;
import com.star.cat.persitent.service.PerManager;
import com.star.cat.persitent.service.PerService;

@Service
@Transactional
public class PerManagerImpl implements PerManager {
	
	@Autowired
	private PerService perService;

	@Override
	public List<CacheNode> tree() {
		List<CacheNode> nodes = new ArrayList<>();
		Map<String,	String> map =perService.getAll();
		if (map.size()>0) {
			Set<String> keys = map.keySet();
			keys.forEach(key->{
				String[] strs = key.split(":");
				for (int i = 0; i < strs.length; i++) {
					CacheNode node = null;
					if (i == 0) { // 根节点
						node = new CacheNode(strs[i], "0", key);
					} else {
						node = new CacheNode(strs[i], strs[i - 1], key);
					}
					nodes.add(node);
				}
			});
			return TreeUtil.bulid(nodes, "0");
		}
		return new ArrayList<>();
	}

	@Override
	public Map findAll() {
		Map<String, Object> map = new HashMap<>();
		perService.getAll().forEach((k,v)->{
			map.put(k, JSON.parse(v));
		});
		return map;
	}

	@Override
	public CacheVo findByKey(String key) {
		PerModel perModel = perService.getModelByKey(key);
		return new CacheVo(perModel.getKey(),JSON.parse(perModel.getValue()), perModel.getExpireTime());
	}

	@Override
	public void removeByKey(String key) {
		perService.delByKey(key);
	}

	@Override
	public void removeAll() {
		perService.expiredAll();
	}

	@Override
	public void extendTime(String key, Long time) {
		perService.extendTime(key,time);
	}

}
